package com.gjy.redis.util.jedis;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-09-30 09:16:39
 */
@Component
public class HashRedisUtil {

    @Resource
    private JedisPool jedisPool;

    /**
     * 设置hash字段值
     */
    public Long hset(String key, String field, String value) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hset(key, field, value);
        }
    }

    /**
     * 批量设置hash字段值
     */
    public String hmset(String key, Map<String, String> hash) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hmset(key, hash);
        }
    }

    /**
     * 获取hash字段值
     */
    public String hget(String key, String field) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hget(key, field);
        }
    }

    /**
     * 批量获取hash字段值
     */
    public List<String> hmget(String key, String... fields) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hmget(key, fields);
        }
    }

    /**
     * 获取所有hash字段和值
     */
    public Map<String, String> hgetAll(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hgetAll(key);
        }
    }

    /**
     * 删除hash字段
     */
    public Long hdel(String key, String... fields) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hdel(key, fields);
        }
    }

    /**
     * 判断hash字段是否存在
     */
    public Boolean hexists(String key, String field) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hexists(key, field);
        }
    }

    /**
     * 获取hash所有字段名
     */
    public Set<String> hkeys(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hkeys(key);
        }
    }

    /**
     * 获取hash所有字段值
     */
    public List<String> hvals(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hvals(key);
        }
    }

    /**
     * 获取hash字段数量
     */
    public Long hlen(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hlen(key);
        }
    }

    /**
     * hash字段自增
     */
    public Long hincrBy(String key, String field, long increment) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hincrBy(key, field, increment);
        }
    }

}

